package com.financing.wap.service.impl;

import com.financing.wap.dao.*;
import com.financing.wap.dto.*;
import com.financing.wap.service.IManagerLicaishiService;
import com.financing.wap.service.IUserService;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.vo.AdQueryVo;
import com.financing.wap.vo.ManagerLicaishiVO;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jfree.util.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.*;

@Service("userService")
public class UserServiceImpl implements IUserService{
	protected Logger log = Logger.getLogger(this.getClass());
	@Autowired
	private IUserDao userDao;
	
	@Autowired
	private IAccountDao accountDao;

	@Autowired
	private IFpFaOfflineUserDao fpFaOfflineUserDao;
	
	@Autowired
	private IUserInfoDao userInfoDaoImpl;
	
	@Autowired
	private IManagerLicaishiService managerLicaishiServiceImpl;
	
	@Autowired
	private IUserWechatDao userWechatDaoImpl;
	
	/*
	 * 根据用户名密码查询用户信息
	 * @see com.financing.wap.service.IUserService#getUserByUF(com.financing.wap.dto.UserDTO)
	 */
	@Override
	public UserDTO getUserByUF(UserDTO user) {

		return userDao.getUserByUF(user);
	}
	/*
	 * 根据用户名密码查询用户信息
	 * @see com.financing.wap.service.IUserService#getUserByUF(com.financing.wap.dto.UserDTO)
	 */
	@Override
	public UserDTO getUser(UserDTO user) throws Exception{

		return userDao.getUser(user);
	}

	/*
	 * FA注册
	 * @see com.financing.wap.service.IUserService#registerUser(com.financing.wap.dto.UserDTO)
	 */
	@Override
	public Map<String,String> registerUser(UserDTO user) {

		Map<String,String> map = new HashMap<String, String>();

		AccountCorpDTO accountCorp = new AccountCorpDTO();
		
		//1 、从image-1.jpg至image-10.jpg随机取一张图片作为FA图像
		try{
			//从image-1.jpg至image-10.jpg随机取一张图片作为FA图像
			String[] filesName = PropertiesUtils.getValue("faUserImageFile").split(";");
			Random r = new Random(System.currentTimeMillis());
			user.setuImage(PropertiesUtils.getValue("faUserImagePath")+filesName[r.nextInt(9)]);
		}catch(Exception e){
			Log.warn("create fa user image error",e);
		}

		//
		
		//2、 查询线下名单是否存在-（补充其他信息）
		FpFaOfflineUserDTO fpFaOfflineUserDto=new FpFaOfflineUserDTO();
		fpFaOfflineUserDto.setMobile(user.getLoginName());
		FpFaOfflineUserDTO faOfflineInfo = fpFaOfflineUserDao.getFaOfflineByUserMobile(fpFaOfflineUserDto);
		
		boolean hasInfo=faOfflineInfo!=null&&StringUtils.isNotBlank(faOfflineInfo.getMobile());
		if(hasInfo){
			user.setMobile(faOfflineInfo.getMobile());
			user.setuEmail(faOfflineInfo.getEmail());
			user.setuCompanyAdd(faOfflineInfo.getCompanyAdd());
			user.setuCompanyName(faOfflineInfo.getCompanyName());
			user.setuJob(faOfflineInfo.getJob());
			user.setuRealName(faOfflineInfo.getName());
			user.setRemark(faOfflineInfo.getRemark());
		}
		
		//3、fp_fa_user 包含 公司线下名单
		 String userId= userDao.isMobileRegisteredForSFA(user.getLoginName());
		if(StringUtils.isBlank(userId)){
			//不存在 就 注册
			userId = userDao.registerUser(user);
		}else{
			user.setId(userId);
			//存在  状态  已注册
			userDao.isMobileUpdateForSFA(user);
		}
		
		//4、注册用户的来源id 是否是  销售人员  ，是： 将用户分配到 销售人员下
		sysAutoAssign(user, map, userId);
		
		//5、添加  用户账户信息
		accountCorp.setUserId(userId);
		accountCorp.setCreateBy(userId.toString());
		accountCorp.setUpdateBy(userId.toString());
		accountDao.addAccount(accountCorp);
		return map;
	}
	/**
	 * 如果没有分配 就自动分配
	 * @param user
	 * @param map
	 * @param userId
	 */
	public void sysAutoAssign(UserDTO user, Map<String, String> map,
			String userId) {
		log.info("registerUser getSourceCode:"+user.getSourceCode());
		
		//4、注册用户的来源id 是否是  销售人员  ，是： 将用户分配到 销售人员下
		if(StringUtils.isNotBlank(user.getSourceCode())&&!"0".equals(user.getSourceCode())){
			
			log.info("registerUser getSourceCode  is not null...........................");
			try {
				//判断是否已被分配
				ManagerLicaishiVO managerLicaishiVo=new ManagerLicaishiVO();
				managerLicaishiVo.setFaUserId(userId);
				int countManagerLicaishiByUser = managerLicaishiServiceImpl.countManagerLicaishiByUser(managerLicaishiVo);
				if(countManagerLicaishiByUser>0){
					log.info("registerUser managerLicaishiVo not null..............");
					return ;
				}
				
				UserDTO userSource  =  userDao.queryUserById(user.getSourceCode());
				String loginName = userSource.getLoginName();
				UserInfoDTO userInfo = userInfoDaoImpl.queryUserInfoForLicaishi(loginName);
				
				log.info("registerUser getSourceCode  loginName:"+loginName+"...........................");
				
				//不为空-存在在销售人员列表中
				if(userInfo != null && StringUtils.isNotBlank(userInfo.getUserId())){
					//需要短信通知 销售人员
					map.put("loginName",loginName);
					
					log.info("registerUser getSourceCode  userInfo:"+userInfo.getUserId()+"...........................");	
					
					//将用户分配到 销售人员下
					ManagerLicaishiVO managerLicaishi = new ManagerLicaishiVO();
					managerLicaishi.setLicaishiIds(userId.toString());
//					managerLicaishiServiceImpl.editManagerLicaishiByUser(managerLicaishi,userInfo);
					managerLicaishi.setSystemUserId(userInfo.getUserId());
					managerLicaishiServiceImpl.batchAddManagerLicaishiUser(managerLicaishi,userInfo);
					
				}
			} catch (SQLException e) {
				log.error("registerUser getSourceCode  is not nul error",e);
			}
		}
	}
	
	/*
	 * 手机号码是否已经被注册
	 * @see com.financing.wap.service.IUserService#isMobileRegistered(java.lang.String)
	 */
	public boolean isMobileRegistered(String mobile){
		return userDao.isMobileRegistered(mobile);
	}

	@Override
	public CorpFaUserDTO getUserById(String userId) {
		return userDao.getUserById(userId);
	}

	@Override
	public String updateFaUserInfo(FaUserDTO dto) {
		
		return userDao.updateFaUserInfo(dto);
	}

	@Override
	public int queryCountBySourceCode(String id) {
		
		return userDao.queryCountBySourceCode(id);
	}
	@Override
	public UserDTO queryUserByMobile(UserDTO user) {
		 UserDTO u = userDao.queryUserByMobile(user);
		//wap_jee_1.1 加入微信信息.
		 if(u!=null){
			FaUserWechatDTO faUserWechatDTO =  new FaUserWechatDTO();
			faUserWechatDTO.setUserId(u.getId());
			try {
				FaUserWechatDTO view = (FaUserWechatDTO)userWechatDaoImpl.queryUserWechatInfo(faUserWechatDTO);
				if(view !=null){
					String headimgurl = view.getHeadimgurl();
					if(StringUtils.isNotBlank(headimgurl)){
						u.setuImage(headimgurl);
					}
					faUserWechatDTO.setNickname(view.getNickname());
					faUserWechatDTO.setHeadimgurl(headimgurl);
					u.setUserWechatDto(faUserWechatDTO);
				}
			} catch (SQLException e) {
				log.error("queryUserByMobile error",e);
			}
		 }
		return u;
	}
	@Override
	public UserDTO queryUserById(String userId) {
		return userDao.queryUserById(userId);
	}
	@Override
	public List<AdQueryVo> queryAdRegInfo(Date createDate) {
		return userDao.queryAdRegInfo(createDate);
	}

	@Override
	public List<UserDTO> getInviteFaListByUserId(Map<String, Object> queryParams) throws Exception{
		return userDao.getInviteFaListByUserId(queryParams);
	}

	@Override
	public int getInviteFaListByUserIdCount(UserDTO user) throws Exception{
		return userDao.getInviteFaListByUserIdCount(user);
	}
	
	//根据登陆名查询
	@Override
	public UserDTO queryUserLoginName(UserDTO loginUser) {
		// TODO Auto-generated method stub
		return userDao.queryUserLoginName(loginUser);
	}
	@Override
	public List<Map<String, Object>> getSFAList(Map<String, Object> queryParams)
			throws Exception {
		return userDao.getSFAList(queryParams);
	}
	@Override
	public int getSFAListCount(Map<String, Object> queryParams)
			throws Exception {
		return userDao.getSFAListCount(queryParams);
	}
	@Override
	public Map<String, Object> getUser(Map<String, Object> queryParams)
			throws Exception {
		return userDao.getUser(queryParams);
	}
	@Override
	public UserDTO getUserToSendEmail(UserDTO user) {
		return userDao.getUserToSendEmail(user);
	}
	@Override
	public FaUserWechatDTO getFaUserWechatDTO(FaUserWechatDTO faUserWechatDTO)
			throws Exception {
		return userDao.getFaUserWechatDTO(faUserWechatDTO);
	}
	@Override
	public UserDTO loadByPaperNo(String idcardno) throws Exception {
		UserDTO user = new UserDTO();
		user.setRealPaperNo(idcardno);
		return userDao.getUser(user);
	}
	@Override
	public void updateUser(UserDTO user) throws Exception {
		 userDao.updateUser(user);
	}
	@Override
	public void updateUserForce(UserDTO user) throws Exception {
		userDao.updateUserForce(user);
		
	}
	@Override
	public List<UserDTO> queryFaImage(List<Integer> ids) {
		
		return userDao.queryFaImage(ids);
	}
	@Override
	public String updatefaUserInfoAutoPass(UserDTO user) {
		return userDao.updatefaUserInfoAutoPass(user);
	}
	
}